import React, { Fragment } from "react";
import { Chart, Geom, Axis, Tooltip, Legend } from "bizcharts";
import DataSet from "@antv/data-set";
import numeral from "numeral";
import moment from "moment";
import autoHeight from "../autoHeight";

@autoHeight()
export default class StackedBar extends React.Component {
  componentWillUnmount() {
    this.chart = null;
  }

  getG2Instance = chart => {
    this.chart = chart;
  };

  render() {
    if (this.chart) {
      this.chart.forceFit();
    }
    const {
      title,
      height = 400,
      padding = [60, 40, 40, 40],
      titleMap = {
        y1: "y1",
        y2: "y2"
      },
      data = [
        {
          x: 0,
          y1: 0,
          y2: 0
        }
      ]
    } = this.props;
    const ds = new DataSet();
    const dv = ds.createView().source(data);
    dv.transform({
      type: "map",
      callback(row) {
        const newRow = { ...row };
        newRow[titleMap.y1] = row.y1;
        newRow[titleMap.y2] = row.y2;
        return newRow;
      }
    }).transform({
      type: "fold",
      fields: [titleMap.y1, titleMap.y2],
      // 展开字段集
      key: "key",
      // key字段
      value: "value" // value字段
    });

    let scale = {};
    if (data.length) {
      scale = {
        x: {
          type: "cat",
          range: [0.04, 0.96],
          formatter: val => moment(val).format("MM.DD")
        },
        value: {
          min: 0
        }
      };
    } else {
      scale = {
        x: {
          type: "linear",
          tickInterval: 1,
          tickCount: 14,
          min: 0,
          max: 14,
          formatter: val =>
            moment()
              .add(val - 15, "days")
              .format("MM.DD")
        },
        value: {
          max: 75,
          min: 0,
          tickInterval: 15
        }
      };
    }
    return (
      <Fragment>
        {title && title}
        <Chart
          height={height}
          data={dv}
          padding={padding}
          forceFit
          scale={scale}
          onGetG2Instance={this.getG2Instance}
        >
          <Legend
            marker="circle"
            position="top-right"
            useHtml={true}
            itemTpl={(value, color, checked, index) => {
              let total = 0;
              const arr = dv.origin;
              for (let i = 0; i < arr.length; i += 1) {
                total += arr[i][`y${index + 1}`];
              }
              const isChecked = checked ? "checked" : "unChecked";
              return `<li class="g2-legend-list-item item-${index} ${isChecked}" data-color="${color}" data-value="${value}" style="cursor: pointer;font-size: 14px; "><i  class="g2-legend-marker" style="border-radius:50%;display:inline-block;margin-right:10px;background-color: ${color};"></i><span class="g2-legend-text" style="color:rgba(0,0,0,.45);">${value}</span><h2 style="font-size:30px;margin-top:5px; margin-bottom:24px; line-height:32px;" >${numeral(
                total
              ).format("0,0")}</h2></li>`;
            }}
            g2-legend={{ whiteSpace: "nowrap" }}
            g2-legend-marker={{ width: "8px", height: "8px" }}
          />
          <Axis name="x" />
          <Axis name="value" />
          <Tooltip
            g2-tooltip={{
              backgroundColor: "rgba(0,0,0,.75)",
              color: "#fff",
              boxShadow: "0px 2px 8px 0px rgba(0,0,0,0.15)"
            }}
            g2-tooltip-value={{
              float: "none",
              marginLeft: "0px"
            }}
            // showTitle={false}
          />
          <Geom
            type="intervalStack"
            position="x*value"
            color={["key", ["#245BDB", "#13C2C2"]]}
            style={{
              stroke: "#fff",
              lineWidth: 1
            }}
            tooltip={[
              "value*key*x",
              (value, key, x) => ({
                title: x,
                name: `${key}：`,
                value: numeral(value).format("0,0")
              })
            ]}
            size={24}
            adjust={[
              {
                type: "dodge",
                marginRatio: 0.5 // 数值范围为 0 至 1，用于调整分组中各个柱子的间距
              }
            ]}
          />
        </Chart>
      </Fragment>
    );
  }
}
